#include "serverthread.h"

ServerThread::ServerThread(int socketDescriptor, Service *service, int waitForAnswer)

{
    this->socketDescriptor = socketDescriptor;
    this->service = service;
    this->waitForAnswer = waitForAnswer;
    nextBlockSize = 0;
}

void ServerThread::run()
{
    QTcpSocket *tcpSocket = new QTcpSocket;
    tcpSocket->setSocketDescriptor(socketDescriptor);
    QDataStream in(tcpSocket);

    forever {
        tcpSocket->waitForReadyRead();

        if(nextBlockSize == 0)
        {
            if(tcpSocket->bytesAvailable() < sizeof(quint16))
            {
                continue;
            }

            in >> nextBlockSize;
        }

        if(tcpSocket->bytesAvailable() < nextBlockSize)
        {
            continue;
        }

        if(waitForAnswer > 0)
        {
            int initialTime = QTime(0, 0, 0).msecsTo(QTime::currentTime());
            int finalTime = initialTime;

            while(finalTime - initialTime < waitForAnswer)
            {
                finalTime = QTime(0, 0, 0).msecsTo(QTime::currentTime());
            }
        }


        QByteArray result = service->execute(in);

        if(!result.isEmpty())
        {
            tcpSocket->write(result);
        }

        nextBlockSize = 0;
        break;

    }
    tcpSocket->disconnectFromHost();
    tcpSocket->waitForDisconnected();
}
